
package com.yadong.smarthome2.connections;

import java.util.ArrayList;
import java.util.List;

public class MessageSendThread extends Thread {
    public enum State {
        IDEL, WORKING
    }
    private List<Runnable> mWorks = new ArrayList<Runnable>();
    private State mState = State.IDEL;
    private volatile boolean mStoped = false;
    private Object mLock = new Object();
    

    public State getSendState() {
        return mState;
    }

    public void addWork(Runnable runnable) {
        synchronized (mLock) {
            mWorks.add(runnable);
            if (mState == State.IDEL) {
                mLock.notify();
            }
        }
    }

    @Override
    public void run() {
        while(!mStoped) {
            synchronized (mLock) {
                if (mWorks.size() <= 0) {
                    try {
                        mState = State.IDEL;
                        mLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Runnable runnable = mWorks.remove(0);
                if(runnable != null) {
                    mState = State.WORKING;
                    runnable.run();
                }
            }
        }
    }
}
